<script>
import CheckinCard from '@/components/CheckinCard/CheckinCard.vue';
import TrainCard from '@/components/TrainCard/TrainCard.vue';
import AdviceCard from '@/components/AdviceCard/AdviceCard.vue';
import Loader from '@/components/Loader/Loader.vue'
import { identity } from '@/util/identity.js'
import { refreshTabBar } from '@/util/tabbar.js'
import MyTabbar from '@/components/MyTabbar/MyTabbar.vue'

export default {
	components: { CheckinCard, TrainCard, AdviceCard, Loader, MyTabbar },
	props: {},
	data() {
		return {
			activeTab: 0, // 当前激活的tab，0为训练，1为建议
			// 训练相关数据
			trainItems: [],
			trainTotalNum: 0,
			trainCurrentPage: 0,
			trainBatchSize: 10,
			trainIsLoading: false,
			trainRefreshing: false, // 训练刷新状态
			// 建议相关数据
			adviceItems: [],
			adviceTotalNum: 0,
			adviceCurrentPage: 0,
			adviceBatchSize: 10,
			adviceIsLoading: false,
			adviceRefreshing: false, // 建议刷新状态
			isFavoriteView: false, // 建议页面的收藏视图状态
			isHealthTeam: false, // 是否为健康团队身份
		};
	},
	methods: {
		// 切换tab
		switchTab(index) {
			this.activeTab = index;
			if (index === 0 && this.trainItems.length === 0) {
				this.getTrainList(); // 切换到训练tab时加载数据
			} else if (index === 1 && this.adviceItems.length === 0) {
				this.getAdviceList(); // 切换到建议tab时加载数据
			}
		},
		
		// 获取训练列表
		getTrainList() {
			if (this.trainIsLoading) return;
			this.trainIsLoading = true;

			this.$request({
				url: '/train/video/push/',
				method: 'GET',
				data: {
					batch_num: this.trainCurrentPage,
					batch_size: this.trainBatchSize,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						const { videos, total_num } = response.data;
						this.trainTotalNum = total_num;
						this.trainItems = this.trainItems.concat(
							videos.map(video => ({
								id: video.id || null,
								imgUrl: null,
								title: video.title,
								content: video.description,
								duration: video.duration_minutes,
							}))
						);
						this.trainCurrentPage++;
					} else {
						console.error('获取训练列表失败');
						console.log(response);
					}
					this.trainIsLoading = false;
				},
				fail: (error) => {
					console.error('请求失败', error);
					this.trainIsLoading = false;
				}
			});
		},
		
		// 获取建议列表
		getAdviceList() {
			const url = this.isFavoriteView ? '/article/collect/get/' : '/article/get/user/';
			if (this.adviceIsLoading) return;
			this.adviceIsLoading = true;

			this.$request({
				url: url,
				method: 'GET',
				data: {
					batch_num: this.adviceCurrentPage,
					batch_size: this.adviceBatchSize,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						console.log(response.data)
						const { articles, total_num } = response.data;
						console.log(articles);
						this.adviceTotalNum = total_num;
						this.adviceItems = this.adviceItems.concat(
							articles.map(article => ({
								mainType: article.article_type === 0 ? "article" : "video",
								item: {
									id: article.id,
									imgUrl: article.article_type === 0 ? article.file_urls[0] : null,
									title: article.title,
									content: article.content,
									is_collected: article.is_collected,
									date: new Date(article.create_date).toLocaleDateString(),
								},
								favored: article.is_collected,
							}))
						);
						this.adviceCurrentPage++;
					} else {
						console.error('获取建议列表失败');
					}
					this.adviceIsLoading = false;
				},
				fail: (error) => {
					console.error('请求失败', error);
					this.adviceIsLoading = false;
				}
			});
		},

		// 发布按钮：发布训练
		publishTrain() {
			uni.navigateTo({ url: '/sub_pages/pages/train_add/train_add' });
		},
		// 发布按钮：发布文章
		publishArticle() {
			uni.navigateTo({ url: '/sub_pages/pages/advice_add/advice_add' });
		},
		
		// 滚动处理 - 训练
		handleTrainScroll(e) {
			const { scrollTop, scrollHeight } = e.detail;
			const threshold = 100; // 距离底部100rpx时触发加载
			
			// 判断是否接近底部
			if (scrollHeight - scrollTop <= threshold + 500) {
				if (this.trainItems.length < this.trainTotalNum && !this.trainIsLoading) {
					this.getTrainList();
				}
			}
		},
		
		// 滚动处理 - 建议
		handleAdviceScroll(e) {
			const { scrollTop, scrollHeight } = e.detail;
			const threshold = 100; // 距离底部100rpx时触发加载
			
			// 判断是否接近底部
			if (scrollHeight - scrollTop <= threshold + 500) {
				if (this.adviceItems.length < this.adviceTotalNum && !this.adviceIsLoading) {
					this.getAdviceList();
				}
			}
		},
		
		// 训练相关方法
		handleTrainDelete(videoId) {
			this.trainItems = this.trainItems.filter(item => item.id !== videoId);
		},
		
		// 建议相关方法
		toggleAdviceView() {
			this.isFavoriteView = !this.isFavoriteView;
			this.adviceItems = [];
			this.adviceCurrentPage = 0;
			this.adviceTotalNum = 0;
			this.getAdviceList();
		},
		
		toggleAdviceFavorite(item, isFavored) {
			const url = isFavored ? '/article/collect/add/' : '/article/collect/remove/';
			this.$request({
				url: url,
				method: 'POST',
				data: {
					article_id: item.id,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						console.log('收藏状态更新成功');
						const index = this.adviceItems.findIndex(i => i.item.id === item.id);
						if (index !== -1) {
							this.adviceItems[index].favored = isFavored;
						}
					} else {
						console.error('收藏状态更新失败');
						console.log(response);
					}
				},
				fail: (error) => {
					console.error('请求失败', error);
				}
			});
		},
		
		navigateToAdviceDetail(id, mainType) {
			if (!id || !mainType) {
				console.error('导航失败：缺少必要参数 id 或 mainType');
				return;
			}
			const url = `../../sub_pages/pages/advice_content/advice_content?id=${id}&mainType=${mainType}`;
			uni.navigateTo({
				url: url,
			});
		},
		
		handleAdviceDelete(adviceId) {
			this.adviceItems = this.adviceItems.filter(item => item.item.id !== adviceId);
		},
		
		// 下拉刷新 - 训练
		onTrainRefresh() {
			if (this.trainRefreshing) return;
			this.trainRefreshing = true;
			
			// 重置数据
			this.trainItems = [];
			this.trainCurrentPage = 0;
			this.trainTotalNum = 0;
			
			// 重新加载数据
			this.$request({
				url: '/train/video/push/',
				method: 'GET',
				data: {
					batch_num: 0,
					batch_size: this.trainBatchSize,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						const { videos, total_num } = response.data;
						this.trainTotalNum = total_num;
						this.trainItems = videos.map(video => ({
							id: video.id || null,
							imgUrl: null,
							title: video.title,
							content: video.description,
							duration: video.duration_minutes,
						}));
						this.trainCurrentPage = 1;
						
						uni.showToast({
							title: '刷新成功',
							icon: 'success',
							duration: 1500
						});
					} else {
						console.error('刷新训练列表失败');
						uni.showToast({
							title: '刷新失败',
							icon: 'none',
							duration: 1500
						});
					}
					this.trainRefreshing = false;
				},
				fail: (error) => {
					console.error('刷新请求失败', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					});
					this.trainRefreshing = false;
				}
			});
		},
		
		// 下拉刷新 - 建议
		onAdviceRefresh() {
			if (this.adviceRefreshing) return;
			this.adviceRefreshing = true;
			
			const url = this.isFavoriteView ? '/article/collect/get/' : '/article/get/user/';
			
			// 重置数据
			this.adviceItems = [];
			this.adviceCurrentPage = 0;
			this.adviceTotalNum = 0;
			
			// 重新加载数据
			this.$request({
				url: url,
				method: 'GET',
				data: {
					batch_num: 0,
					batch_size: this.adviceBatchSize,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						const { articles, total_num } = response.data;
						this.adviceTotalNum = total_num;
						this.adviceItems = articles.map(article => ({
							mainType: article.article_type === 0 ? "article" : "video",
							item: {
								id: article.id,
								imgUrl: article.article_type === 0 ? article.file_urls[0] : null,
								title: article.title,
								content: article.content,
								is_collected: article.is_collected,
								date: new Date(article.create_date).toLocaleDateString(),
							},
							favored: article.is_collected,
						}));
						this.adviceCurrentPage = 1;
						
						uni.showToast({
							title: '刷新成功',
							icon: 'success',
							duration: 1500
						});
					} else {
						console.error('刷新建议列表失败');
						uni.showToast({
							title: '刷新失败',
							icon: 'none',
							duration: 1500
						});
					}
					this.adviceRefreshing = false;
				},
				fail: (error) => {
					console.error('刷新请求失败', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					});
					this.adviceRefreshing = false;
				}
			});
		},
	},
	beforeDestroy() {
		// 清理工作（如果需要的话）
	},
	// 页面显示时加载数据和刷新身份
	onShow() {
		// 刷新身份
		this.isHealthTeam = identity.isHealthTeam();
		
		// 刷新tabBar
		refreshTabBar();
		
		// 如果是首次显示（没有数据），加载初始数据
		if (this.activeTab === 0 && this.trainItems.length === 0) {
			this.getTrainList();
		} else if (this.activeTab === 1 && this.adviceItems.length === 0) {
			this.getAdviceList();
		}
	},
};
</script>

<template>
	<view class="flex-col justify-start page">
		<!-- Tab切换栏 -->
		<view class="tab-bar">
			<view 
				class="tab-item" 
				:class="{ 'active': activeTab === 0 }" 
				@click="switchTab(0)"
			>
				训练
			</view>
			<view 
				class="tab-item" 
				:class="{ 'active': activeTab === 1 }" 
				@click="switchTab(1)"
			>
				建议
			</view>
		</view>
		
		<!-- 训练内容 -->
		<view v-if="activeTab === 0" class="flex-col group_1">
			<checkin-card class="section"></checkin-card>
			
			<Loader :loading="trainIsLoading">
				<scroll-view 
					class="scroll-container"
					scroll-y
					refresher-enabled
					:refresher-triggered="trainRefreshing"
					@refresherrefresh="onTrainRefresh"
					@scroll="handleTrainScroll"
					refresher-background="#f5f5f5"
				>
					<view class="flex-col list">
						<train-card
							class="list-item mt-12"
							v-for="(item, index) in trainItems"
							:key="index"
							:item="item"
							@delete="handleTrainDelete"
						></train-card>
					</view>
				</scroll-view>
			</Loader>
			
			<!-- 发布训练浮动按钮（仅健康团队显示） -->
			<view v-if="isHealthTeam" class="fab" @click="publishTrain">
				<text class="fab-text">发布训练</text>
			</view>
		</view>
		
		<!-- 建议内容 -->
		<view v-if="activeTab === 1" class="flex-col justify-start group_1">
			<view class="flex-row group-header">
				<view class="flex-row justify-center items-center equal-division-item section_4">
					<image class="image_7"
						src="/static/icon/report-pink.svg" />
					<text class="font text_3 ml-8">我的报告</text>
				</view>
				<view class="flex-row justify-center items-center equal-division-item section_5 ml-10" @click="toggleAdviceView">
					<image class="image_7"
						src="/static/icon/star-yellow.svg" />
					<text class="font text_4 ml-8">{{ isFavoriteView ? '所有文章' : '我的收藏' }}</text>
				</view>
			</view>
			
			<Loader :loading="adviceIsLoading">
				<scroll-view 
					class="scroll-container"
					scroll-y
					refresher-enabled
					:refresher-triggered="adviceRefreshing"
					@refresherrefresh="onAdviceRefresh"
					@scroll="handleAdviceScroll"
					refresher-background="#f5f5f5"
				>
					<view class="flex-col advice-list">
						<advice-card 
							class="list-item mt-12" 
							v-for="(item, index) in adviceItems" 
							:key="index" 
							:item="item.item" 
							:mainType="item.mainType" 
							:favored="item.favored" 
							@toggle-favorite="toggleAdviceFavorite"
							@delete="handleAdviceDelete"
							@tap="navigateToAdviceDetail(item.item.id, item.mainType)"
						></advice-card>
					</view>
				</scroll-view>
			</Loader>
			
			<!-- 发布文章浮动按钮（仅健康团队显示） -->
			<view v-if="isHealthTeam" class="fab" @click="publishArticle">
				<text class="fab-text">发布文章</text>
			</view>
		</view>
		<my-tabbar />
	</view>
</template>

<style scoped lang="css">
.page {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	padding-bottom: 150rpx;
}

.scroll-container {
	width: 100%;
	height: calc(100vh - 430rpx);
}

.tab-bar {
	display: flex;
	background-color: #ffffff;
	border-bottom: 1rpx solid #e5e5e5;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	font-size: 32rpx;
	color: #666666;
	position: relative;
}

.tab-item.active {
    color: #F26A77;
    font-weight: bold;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 4rpx;
    background-color: #F26A77;
    border-radius: 2rpx;
}

.group_1 {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.section {
	margin: 24rpx 24rpx 0 24rpx;
	flex-shrink: 0;
}

.list {
	padding: 20rpx 24rpx 0 24rpx;
}


.group {
	padding: 30rpx 34rpx 0 36rpx;
}

.group-header {
	padding: 20rpx 24rpx 12rpx 24rpx;
	background-color: #f5f5f5;
	flex-shrink: 0;
}

.advice-list {
	padding: 0 24rpx;
}

.equal-division-item {
	flex: 1 1 330rpx;
}

.section_4 {
	padding: 20rpx 24rpx;
	background-color: rgba(242, 106, 119, 0.12);
	border-radius: 20rpx;
	height: 104rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.image_7 {
	width: 56rpx;
	height: 56rpx;
}

.font {
	font-size: 30rpx;
	line-height: 30rpx;
}

.text_3 {
	color: #99434b;
}

.section_5 {
	padding: 20rpx 24rpx;
	background-color: rgba(244, 174, 130, 0.20);
	border-radius: 20rpx;
	height: 104rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.text_4 {
	color: #996d51;
	line-height: 31.28rpx;
}

.list-item {
	border-radius: 16rpx;
	background: #ffffff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.list-item:first-child {
	margin-top: 0;
}
.fab {
  position: fixed;
  right: 36rpx;
  bottom: 210rpx;
  background-color: #F26A77;
  color: #FFFFFF;
  padding: 20rpx 28rpx;
  border-radius: 9999rpx;
  box-shadow: 0 8rpx 20rpx rgba(0,0,0,0.15);
}
.fab-text { font-size: 28rpx; }

</style>

<style>
page {
  background-color: #f5f5f5;
  height: 100vh;
  overflow: hidden;
  padding-bottom: 150rpx;
}
</style>
